package src.Fourteen;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyMoveBackground extends JFrame {

    private JLabel label;

    public static void main(String[] args) {
        KeyMoveBackground keyMoveBackground = new KeyMoveBackground();
    }

    public KeyMoveBackground(){
        super();
        setResizable(false);
        getContentPane().setLayout(null);
        setTitle("方向键移动背景");
        setBounds(100,100,500,375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label = new JLabel();
        ImageIcon icon = new ImageIcon(getClass().getResource("2.jpg"));
        ImageIcon glassImg = new ImageIcon(getClass().getResource("2.png"));
        label.setIcon(icon);
        label.setSize(icon.getIconWidth(),icon.getIconHeight());
        label.setLocation(-icon.getIconWidth()/3,-icon.getIconHeight()/3);
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                super.keyTyped(e);
            }

            @Override
            public void keyPressed(KeyEvent e) {
                do_label_keyPressed(e);
            }

            @Override
            public void keyReleased(KeyEvent e) {
                super.keyReleased(e);
            }
        });

        getContentPane().add(label);
        JLabel glassLabel = new JLabel(glassImg);
        JPanel glassPane = new JPanel(new BorderLayout());
        glassPane.add(glassLabel,BorderLayout.CENTER);
        glassPane.setOpaque(false);
        setGlassPane(glassPane);
        getGlassPane().setVisible(true);
        this.setVisible(true);
        this.setSize(500,500);

    }

    protected void do_label_keyPressed(final KeyEvent e){
        int code = e.getKeyCode();
        Point location = label.getLocation();
        int step = 3;
        switch (code){
            case KeyEvent.VK_RIGHT:
                if(location.x >(getWidth()-label.getWidth())){
                    label.setLocation(location.x-step,location.y);
                }
                break;
            case KeyEvent.VK_LEFT:
                if(location.x < 0){
                    label.setLocation(location.x+step,location.y);
                }
                break;
            case KeyEvent.VK_DOWN:
                if(location.y > (getHeight()-label.getHeight())){
                    label.setLocation(location.x,location.y-step);
                }
                break;
            case KeyEvent.VK_UP:
                if(location.y < 0){
                    label.setLocation(location.x,location.y+step);
                }
                break;
            default:
                break;
        }
    }
}
